#include <pthread.h>
#include <unistd.h>
#include <signal.h>
 
#define SIGRESUME SIGUSR2
#define SIGSUSPEND SIGUSR1
#define SIGPQUIT SIGQUIT

void register_sus_sig(void);

/* Thread specied var, the status*/
static __thread int g_bSuspend; //线程范围内变量



void suspend_handler(int signum) {
    g_bSuspend = 1;
    sigset_t nset;
    pthread_sigmask(0, NULL, &nset);
    /* make sure that the resume is not blocked*/
    sigdelset(&nset, SIGRESUME);
    while(g_bSuspend) sigsuspend(&nset); //确定只能通过修改g_bSuspend变量唤醒线程
}
 
void resume_handler(int signum) {
    g_bSuspend = 0;
}

void pquit_handler(int signum) {
    pthread_exit(NULL);
}

void register_pquit_sig(void) {
    struct sigaction pquitsa;
    pquitsa.sa_handler =  pquit_handler;
    sigemptyset(&pquitsa.sa_mask);
    pquitsa.sa_flags = 0;
    sigaction(SIGPQUIT, &pquitsa, NULL);
}

void register_sus_sig(void) {
    struct sigaction suspendsa;
    struct sigaction resumesa;
    sigemptyset(&suspendsa.sa_mask);
    resumesa.sa_flags = suspendsa.sa_flags = 0;
    resumesa.sa_mask = suspendsa.sa_mask;
    suspendsa.sa_handler =  suspend_handler;
    sigaddset(&suspendsa.sa_mask, SIGRESUME);
    sigaction( SIGSUSPEND, &suspendsa, NULL);
    resumesa.sa_handler = resume_handler;
    sigaddset(&resumesa.sa_mask, SIGSUSPEND);
    sigaction( SIGRESUME, &resumesa, NULL);
}

/******************Test Code*****************
#include <stdio.h>
void* task1(void *param) {
    while(1) {
        printf("***************************\n");
        sleep(1);
    }
}
 

int main()
{
    register_sus_sig();
    pthread_t runTh1;
    pthread_create(&runTh1, NULL, task1, NULL);
    while( 1 ) {
        getchar();
        pthread_kill(runTh1, SIGSUSPEND);
        getchar();
        pthread_kill(runTh1, SIGRESUME);

    }
    return 0;
}
********************************************/
